package gold.digger;

import gold.utils.InputUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC934 {
    public long startExecuteTime = System.currentTimeMillis();


    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * 多源BFS求两个集合最短路径，好思路，好题目
     * @return:
     */
    class Solution {
        public int shortestBridge(int[][] A) {
            int R = A.length, C = A[0].length;
            int[][] colors = getComponents(A);

            Queue<Node> queue = new LinkedList();
            Set<Integer> target = new HashSet();

            for (int r = 0; r < R; ++r)
                for (int c = 0; c < C; ++c) {
                    if (colors[r][c] == 1) {
                        queue.add(new Node(r, c, 0));
                    } else if (colors[r][c] == 2) {
                        target.add(r * C + c);
                    }
                }

            // 这里使用队列来BFS，并且还是多源BFS，犀利
            while (!queue.isEmpty()) {
                Node node = queue.poll();
                if (target.contains(node.r * C + node.c))
                    return node.depth - 1;
                for (int nei : getNeighbors(A, node.r, node.c)) {
                    int nr = nei / C, nc = nei % C;
                    if (colors[nr][nc] != 1) {
                        queue.add(new Node(nr, nc, node.depth + 1));
                        colors[nr][nc] = 1;
                    }
                }
            }

            throw null;
        }

        public int[][] getComponents(int[][] A) {
            int R = A.length, C = A[0].length;
            int[][] colors = new int[R][C];
            int t = 0;

            for (int r0 = 0; r0 < R; ++r0)
                for (int c0 = 0; c0 < C; ++c0)
                    if (colors[r0][c0] == 0 && A[r0][c0] == 1) {
                        // Start DFS, note that: 该处使用栈来模拟DFS递归调用，实在是精妙
                        Stack<Integer> stack = new Stack();
                        stack.push(r0 * C + c0);
                        colors[r0][c0] = ++t;

                        while (!stack.isEmpty()) {
                            int node = stack.pop();
                            int r = node / C, c = node % C;
                            for (int nei : getNeighbors(A, r, c)) {
                                int nr = nei / C, nc = nei % C;
                                if (A[nr][nc] == 1 && colors[nr][nc] == 0) {
                                    colors[nr][nc] = t;
                                    stack.push(nr * C + nc);
                                }
                            }
                        }
                    }

            return colors;
        }

        public List<Integer> getNeighbors(int[][] A, int r, int c) {
            int R = A.length, C = A[0].length;
            List<Integer> ans = new ArrayList();
            if (0 <= r - 1) ans.add((r - 1) * R + c);
            if (0 <= c - 1) ans.add(r * R + (c - 1));
            if (r + 1 < R) ans.add((r + 1) * R + c);
            if (c + 1 < C) ans.add(r * R + (c + 1));
            return ans;
        }
    }

    class Node {
        int r, c, depth;

        Node(int r, int c, int d) {
            this.r = r;
            this.c = c;
            depth = d;
        }
    }

    class Solution_Complex_Thought {
        /**
         * Created by fanzhenyu02 on 2020/6/27.
         * Union Find 算法实现
         */
        public class UF {
            // 连通分量个数
            private int count;
            // 存储一棵树
            private int[] parent;
            // 记录树的“重量”
            private int[] size;

            public UF(int n) {
                this.count = n;
                parent = new int[n];
                size = new int[n];
                for (int i = 0; i < n; i++) {
                    parent[i] = i;
                    size[i] = 1;
                }
            }

            /* 将 p 和 q 连接 */
            public void union(int p, int q) {
                int rootP = find(p);
                int rootQ = find(q);
                if (rootP == rootQ)
                    return;

                // 小树接到大树下面，较平衡
                if (size[rootP] > size[rootQ]) {
                    parent[rootQ] = rootP;
                    size[rootP] += size[rootQ];
                } else {
                    parent[rootP] = rootQ;
                    size[rootQ] += size[rootP];
                }
                count--;
            }

            /* 判断 p 和 q 是否连通 */
            public boolean connected(int p, int q) {
                int rootP = find(p);
                int rootQ = find(q);
                return rootP == rootQ;
            }

            private int find(int x) {
                while (parent[x] != x) {
                    // 进行路径压缩
                    parent[x] = parent[parent[x]];
                    x = parent[x];
                }
                return x;
            }

            /* 返回图中有多少个连通分量 */
            public int count() {
                return count;
            }

            /* 返回图中联通集合 */
            public Map<Integer, List<Integer>> outputAggregateSet(int n) {
                Map<Integer, List<Integer>> aggregateMap = new HashMap<>();

                // 共有n个集合
                for (int i = 0; i < n; i++) {
                    int parentId = find(i);
                    if (!aggregateMap.containsKey(parentId)) aggregateMap.put(parentId, new ArrayList<>());
                    aggregateMap.get(parentId).add(i);
                }

                System.out.println(aggregateMap.toString());
                return aggregateMap;
            }
        }

        int n = 2;

        public int shortestBridge(int[][] grid) {
            n = grid.length;
            int firstFather = -1, secondFather = -1;

            UF uf = new UF(n * n + 1);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < j; j++) {
                    if (grid[i][j] == 1) {
                        int id = getId(i, j);
                        if (firstFather == -1) {
                            firstFather = id;
                            BFSTravelUF(grid, i, j, uf);
                        } else if (!uf.connected(firstFather, id)) {
                            if (secondFather == -1) secondFather = id;
                            else uf.union(secondFather, id);
                        }
                    }
                }
            }

            // 之后两个集合进行双重for循环计算最短距离
            return Integer.MAX_VALUE;
        }

        public int getId(int i, int j) {
            return i * n + j;
        }

        public void BFSTravelUF(int[][] grid, int i, int j, UF uf) {
            Deque<int[]> deque = new LinkedList<>();
            deque.push(new int[]{i, j});
            while (!deque.isEmpty()) {
                int[] cur = deque.pollFirst();
                int x = cur[0], y = cur[1];

                if (x > 0 && grid[x - 1][y] == 1 && !uf.connected(getId(x, y), getId(x - 1, y))) {
                    uf.union(getId(x, y), getId(x - 1, y));
                    deque.push(new int[]{x - 1, y});
                }

                if (x + 1 < n && grid[x + 1][y] == 1 && !uf.connected(getId(x, y), getId(x + 1, y))) {
                    uf.union(getId(x, y), getId(x + 1, y));
                    deque.push(new int[]{x + 1, y});
                }

                if (y > 0 && grid[x][y - 1] == 1 && !uf.connected(getId(x, y), getId(x, y - 1))) {
                    uf.union(getId(x, y), getId(x, y - 1));
                    deque.push(new int[]{x, y - 1});
                }

                if (y + 1 < n && grid[x][y + 1] == 1 && !uf.connected(getId(x, y), getId(x, y + 1))) {
                    uf.union(getId(x, y), getId(x, y + 1));
                    deque.push(new int[]{x, y + 1});
                }
            }
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[1,2,3]");
        System.out.println(solution.toString());
    }

    public static void main(String[] args) throws Exception {
        LC934 an = new LC934();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
